-- ================================================
-- Template generated from Template Explorer using:
-- Create Procedure (New Menu).SQL
--
-- Use the Specify Values for Template Parameters 
-- command (Ctrl-Shift-M) to fill in the parameter 
-- values below.
--
-- This block of comments will not be included in
-- the definition of the procedure.
-- ================================================
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE GetCustomerLiability
	-- Add the parameters for the stored procedure here
	@startDate datetime,
	@endDate datetime,
	@customerIds nvarchar(500)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	select
		null as [DocNo],
		lia.CustomerId,
		null as [Customer],
		null as IssuedDate,
		null as [LineNo],
		null as Description,
		sum(lia.Spend) - sum(lia.Receipt) as StartLiability,
		null as Spend,
		null as Receipt,
		null as Note,
		null as Note2		
	from Liabilities lia
		inner join SplitIdsToTables(@customerIds) ids on lia.CustomerId = ids.Id
	where (@startDate is null or lia.IssuedDate < @startDate) 
	group by lia.CustomerId
		
	union
	
	select
		case when sto.DocumentNo is null then rep.DocumentNo else sto.DocumentNo end as [DocNo],
		lia.CustomerId,
		cus.Name as [Customer],
		lia.IssuedDate,
		lia.[LineNo] as [LineNo],
		lia.Description,
		null as StartLiability,
		lia.Spend,
		lia.Receipt,
		lia.Note as Note,
		lia.Note2 as Note2
	from Liabilities lia
		left join StockOuts sto on lia.StockOutId = sto.Id
		left join Receipts rep on lia.ReeiptId = rep.Id
		left join Customers cus on cus.Id = lia.CustomerId
		inner join SplitIdsToTables(@customerIds) ids on lia.CustomerId = ids.Id
	where (@startDate is null or lia.IssuedDate >= @startDate) and
		  (@endDate is null or lia.IssuedDate <= @endDate)

	order by CustomerId, IssuedDate

END
GO
